import axios from 'axios'
import { createrefreshToken, addRequest } from './server'
//创建axios实例
const instance = axios.create({
    baseURL: "http://127.0.0.1:8000/",
    timeout: 50000,
    method: "get"
})
//配置请求拦截器
instance.interceptors.request.use((config => {
    //获取sessionStorage中的token
    let accessToken = sessionStorage.getItem("accessToken")
    //设置请求头
    config.headers.accesstoken = accessToken
    return config
}), err => {
    return Promise.reject(err)
})
//配置响应拦截器
instance.interceptors.response.use((function (data) {
    let { config } = data
    return new Promise((resolve, reject) => {
        if (data.data.code === 401) { // 短token失效时执行
            addRequest(() => resolve(instance(config)))
            //调用接口请求新的token
            createrefreshToken()
        } else {
            // 将响应数据返回
            resolve(data)
        }
    })
}), err => {
    return Promise.reject(err)
})

export default instance